<template>
  <div class="pages newWhole">
    <div class="pageLevel" v-if="!sub">
      <div class="header">
        <label for v-if="soUrce!='5'">来源</label>
        <el-select v-if="soUrce!='5'" width="100px" v-model="activeOrigin" placeholder="请选择" size="small">
          <el-option label="全部来源" value></el-option>
          <el-option label="自主创建" value="0"></el-option>
          <el-option v-if='isShop!=1' label="上级分配" value="2"></el-option>
          <el-option v-if='isShop!=0' label="下级自建" value="1"></el-option>
        </el-select>
        <label for v-if="soUrce!='5' && isShop==1">门店</label>
        <el-select v-if="soUrce!='5' && isShop==1" v-model="selectedShop " placeholder="请选择" size="small">
          <el-option v-for="(item,key) in shopOption" :key="key" :label="item.name" :value="item.baseShopId"></el-option>
        </el-select>
        <el-input v-model="activeName" class="search-input" placeholder="请输入活动名称搜索" size="small"></el-input>
        <el-button type="primary" width="10px" size="mini" @click="grabble">搜索</el-button>
        <el-button type="primary" size="mini" v-if="setRole('新增/编辑')" @click="paymentDialogVisibleOne = true,actRadio=4">新增</el-button>
        <el-button type="primary" size="mini" v-if="setRole('分配')" @click="_distribution(0)">分配</el-button>
      </div>

      <div class="shopContent">
        <el-table ref="multipleActTable" :data="tableData" tooltip-effect="dark" style="width: 100%" @selection-change="priceList.handleMultipleSelect" :row-key="getRowKeys">
          <!-- <template slot-scope="scope"> -->
          <el-table-column type="selection" :selectable="puStatus" v-if="soUrce!='5'"></el-table-column>
          <!-- </template> -->
          <el-table-column label="活动名称" prop="activityName"></el-table-column>
          <el-table-column prop="activityType" align="center" label="活动类型" :formatter="activityType"></el-table-column>
          <el-table-column prop="scopeArea" align="center" label="适用范围">
            <template slot-scope="scope">
              <span v-for="(item,key) in scope.row.scopeArea" :key="key">{{item}} &nbsp;</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="活动时间">
            <template slot-scope="scope">{{scope.row.activityStartTime}} 至 {{scope.row.activityEndTime}}</template>
          </el-table-column>
          <el-table-column prop="activitySource" align="center" label="来源" :formatter="activitySource" v-if="soUrce!='5'"></el-table-column>
          <el-table-column prop="status" width="160px" label="状态" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.activityState ==2">已过期</span>
              <el-switch v-else v-model="scope.row.status" active-color="#13ce66" class="demo" active-text="上架" inactive-text="下架" active-value="0" inactive-value="1" @click.native="onChangeStatus(scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="operation" width="200px" align="center" label="操作">
            <template slot-scope="scope">
              <el-button @click="subtract(1,scope.row,1)" type="text" v-if="!(scope.row.activityState == 0 && setRole('新增/编辑') && scope.row.activitySource==0)">查看</el-button>
              <el-button @click="subtract(0,scope.row,0)" type="text" v-if="scope.row.activityState == 0 && setRole('新增/编辑') && scope.row.activitySource==0">编辑</el-button>
              <el-button type="text" v-if="setRole('分配')&&scope.row.activitySource==0" @click="_distribution(1,scope.row.id,scope.row.activityName)">查看已分配</el-button>
              <el-button size="mini" v-if="setRole('新增/编辑')" :disabled="(scope.row.activitySource!='0'||scope.row.activityState=='2')" @click="deleteRows(scope.row.id,scope.row.activityState)" type="text">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <page-unit :pageData="pageData" :func="information"></page-unit>
      </div>

      <!-- 弹框 -->
      <el-dialog title="选择活动类型" :visible.sync="paymentDialogVisibleOne" width="600px" center :show-close="false" :close-on-click-modal="false" :close-on-press-escape="false">
        <template>
          <div class="cont">
            <el-radio-group v-model="actRadio">
              <el-radio :label="4">满减</el-radio>
              <el-radio :label="3">满折</el-radio>
            </el-radio-group>
          </div>
          <div class="cont">
            <el-button algin="center" @click="sureAdd" type="primary">确定</el-button>
            <el-button algin="center" @click="paymentDialogVisibleOne = false">取消</el-button>
          </div>
        </template>
      </el-dialog>
      <el-dialog :title="Elastic" :visible.sync="distribution.dialog" :close-on-click-modal="false" :close-on-press-escape="false">
        <div class="tableSearch">
          <el-form label-width="100px" class="demo-ruleForm">
            <el-form-item label label-width="15px">
              <el-input class="input" v-model="selectdatas.orgKey" size="small" placeholder="请输入商户名称"></el-input>
            </el-form-item>
            <el-form-item label label-width="15px">
              <el-button type="primary" icon="el-icon-search" size="mini" @click="searchSelectOrg" class="Button">查询</el-button>
            </el-form-item>
            <el-form-item label label-width="15px">
              <el-button type="primary" @click="cancel()" size="mini" v-if="unallocates && setRole('分配')">批量取消分配</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-table :data="shopList" ref="multipleTable" max-height="300" @selection-change="distribution.handleMultipleSelect" :row-key="getRowKeys">
          <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
          <el-table-column type="index" label="序号" width="50"></el-table-column>
          <el-table-column property="name" label="门店名称" align="center"></el-table-column>
          <el-table-column property="shopCode" label="编号" align="center"></el-table-column>
          <el-table-column v-if="unallocates" prop="name" align="center" label="操作" width="280">
            <template slot-scope="scope">
              <el-button size="small" @click="cancel(scope.row.id)" type="text" class="addDetail">取消分配</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="operationBox StoreBranch" style="margin-top:20px;">
          <el-button type="primary" @click="immediateAllocation" size="medium" v-if="!unallocates" style="margin-right:10px;">立即分配</el-button>
          <el-button plain @click="distribution.dialog=false,Sub" size="medium">返回</el-button>
        </div>
      </el-dialog>
    </div>

    <div class="pageLevel" v-else>
      <router-view></router-view>
    </div>
  </div>
</template>

<script>
import pageUnit from "@/components/Page";
import StoreBranch from "@/components/StoreBranch";
import { mapState } from "vuex";
import axios from "axios";
import state from "@/util/state";
import utils from "@/util";
import { TableHandle } from "@/util/class";
import {
  findActivityListPage,
  selectBaseShopPageList,
  offActivity,
  markettoLowerShop,
  distributionShopList,
  cancelDistribution
} from "@/api";
export default {
  components: {
    pageUnit
  },

  data() {
    return {
      pageData: {
        pageSize: 20,
        currentPage: 1,
        totalItems: 0,
        pageSizeArr: [5, 10, 20]
      },
      pagination: 1,
      showValig: false,
      multipleSelection: [],
      tableData: [],
      valueTwo: "",
      activeName: "",
      paymentDialogVisibleOne: false,
      paymentDialogVisibleTwo: false,
      worth: true, //开关,
      isShow: "",
      selectdata: {
        selected: "",
        state: ""
      },
      selectedShop: "",
      pageNum: 1,
      pageSize: 20, //页数
      totalItems: 0,
      optionsOne: [
        {
          value: "",
          label: "全部来源"
        },
        {
          value: 0,
          label: "自主创建"
        },
        {
          value: 1,
          label: "下级自建"
        },
        {
          value: 2,
          label: "上级分配"
        }
      ],
      shopOption: [],
      value: "",
      original: [], //原本展示数据
      searchData: [], //搜索后的数据展示
      activeOrigin: "", //来源
      actRadio: 4, //新增
      value1: true,
      distribution: new TableHandle(), //分配门店
      priceList: new TableHandle(), //分配门店
      Elastic: "",
      integralMulti: [],
      selectdatas: {
        orgKey: ""
      },
      unallocates: false,
      revise: [],
      priceId: "", //编辑方案时id
      addpriceShopType: "",
      addpriceShopId: "", //查看变价商品id
      shopList: [], //分配门店数组
      activityIds: "",
      nameType: "",
      idType: "",
      getRowKeys(row) {
        return row.id; // 获取row的key值
      },
      actName: ""
    };
  },
  computed: mapState([
    "merchantId",
    "sub",
    "companyName",
    "isShop",
    "power",
    "soUrce"
  ]),
  watch: {
    sub: {
      handler: function(val, oldVal) {
        if (oldVal != null && val == false) {
          this.information();
        }
      },
      deep: true
    }
  },
  created() {},
  mounted() {
    this.information();
    if (this.isShop == 1) {
      this.getStoreList();
    } else {
      this.shopOption = [
        {
          baseShopId: this.merchantId,
          name: this.companyName
        }
      ];
    }
  },

  methods: {
    puStatus(row) {
      return row.activitySource == 0;
    },
    //配置权限
    setRole(key) {
      return utils.selectTitle(this.power, key);
    },
    activitySource: state.activitySource,
    activityType: state.activityType,
    // 获取门店
    getStoreList() {
      selectBaseShopPageList({
        businessId: this.merchantId,
        type: "3"
      }).then(res => {
        let a = {
          baseShopId: "",
          name: "全部"
        };
        res.data.list.unshift(a);
        this.shopOption = res.data.list;
        this.selectedShop = "";
      });
    },
    information() {
      //获取商品数据
      let data = {
        activitySource: this.activeOrigin,
        activityName: this.activeName,
        pageSize: this.pageData.pageSize,
        pageNum: this.pageData.currentPage,
        activityTypeList: "3,4",
        companyId: this.merchantId,
        shopId: this.selectedShop
      };
      findActivityListPage(data).then(res => {
        if (res.code == 200) {
          this.tableData = res.data.list;
          this.pageData.totalItems = res.data.totalPage;
          for (let i = 0; i < this.tableData.length; i++) {
            const element = this.tableData[i];
            element.activityStartTime = utils.foryear(
              parseInt(element.activityStartTime)
            );
            element.activityEndTime = utils.foryear(
              parseInt(element.activityEndTime)
            );
            element.status = "" + element.status;
          }
        }
      });
    },

    sureAdd() {
      this.paymentDialogVisibleOne = false;
      utils.routerTo(
        "/marketing-center/pos-activity/new-whole/whole-moneyOff",
        {
          radio: this.actRadio,
          id: "",
          status: "2"
        }
      );
    },
    // 满减满折查看页面
    subtract(radio, row, status) {
      utils.routerTo(
        "/marketing-center/pos-activity/new-whole/whole-moneyOff",
        {
          radio: row.activityType,
          id: row.id,
          status: status
        }
      );
    },
    paymentOne() {
      //分配
      this.paymentDialogVisibleTwo = true;
    },
    paymentTwo() {
      //查看已分配
      this.paymentDialogVisibleTwo = true;
      this.isShow = true;
    },
    dialogVis(e) {
      //触发自定义事件dialogVis
      this.paymentDialogVisibleTwo = e;
      console.log("e:", e);
    },
    grabble() {
      this.information();
    },
    onChangeStatus(row, dr) {
      let message = "确定要上架该内容吗",
        tipmsg = "上架成功",
        status = 0;

      if (row.status == 1) {
        message = "确定要下架该内容吗";
        tipmsg = "下架成功";
        status = 1;
      }
      let changeData = {
        activityId: row.id,
        dr: dr,
        status: status
      };
      this.$confirm(message, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(() => {
          offActivity(changeData).then(res => {
            if (res.code === 200) {
              this.$message({
                type: "success",
                message: tipmsg
              });
              this.information();
            } else {
              this.$message.error(res.msg);
            }
          });
        })
        .catch(() => {
          this.information();
        });
    },
    // 分配的门店列表
    _distributionlistPage(pageSize, pageNum) {
      let Data = {
        pageNum: pageNum,
        pageSize: pageSize,
        businessId: this.merchantId,
        status: 0,
        nameOrCode: this.selectdatas.orgKey,
        type: "3"
      };
      selectBaseShopPageList(Data).then(res => {
        this.distribution.pageData.totalItems = res.data.pageTotal;
        this.shopList = res.data.list;
      });
    },
    // 门店查询
    searchSelectOrg() {
      if (this.nameType == "0") {
        this._distributionlistPage();
      } else {
        this._distribution(this.nameType, this.idType);
      }
    },
    // 分配
    _distribution(name, id, actName) {
      this.nameType = name;
      this.idType = id;
      this.actName = actName;
      if (name == "0") {
        this.Elastic = "选择门店";
        if (this.priceList.isSelect(2, this, "请先选择活动！")) {
          this.distribution.dialog = true;
          this.unallocates = false;
          this._distributionlistPage();
        }
      } else {
        this.activityIds = id;
        this.Elastic = "已分配门店-" + this.actName;
        this.unallocates = true;
        this.distribution.dialog = true;
        let data = {
          activityId: id
        };
        distributionShopList(data).then(res => {
          if (res.code == "200") {
            if (res.data != null) {
              this.shopList = res.data;
            } else {
              this.shopList = [];
            }
          }
        });
      }
    },
    // 立即分配
    immediateAllocation() {
      let shopIds = [];
      let activityIds = [];
      this.distribution.multipleSelectTable.forEach(i => {
        shopIds.push(i.id);
      });
      this.priceList.multipleSelectTable.forEach(i => {
        activityIds.push(i.id);
      });
      let data = {
        shopIds: shopIds.toString(),
        activityIds: activityIds.toString()
      };
      markettoLowerShop(data).then(res => {
        if (res.code == "200") {
          this.$refs.multipleActTable.clearSelection();
          this.$refs.multipleTable.clearSelection();
          this.distribution.dialog = false;
          this.$message.success(res.msg);
        }
      });
    },
    // 取消分配
    cancel(id = "") {
      let shopIds = [];
      this.distribution.multipleSelectTable.forEach(i => {
        shopIds.push(i.id);
      });
      let shopId;
      if (id != "") {
        shopId = id;
      } else {
        shopId = shopIds.toString();
      }
      let data = {
        activityId: this.activityIds,
        shopIds: shopId
      };
      if (id != "") {
        this.$confirm("确定要取消对本门店的分配吗？", {
          center: true,
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          closeOnClickModal: false,
          closeOnPressEscape: false
        }).then(() => {
          cancelDistribution(data).then(res => {
            if (res.code == 200) {
              this.$refs.multipleTable.clearSelection();
              this._distribution(this.nameType, this.idType, this.actName);
              this.$message.success(res.msg);
            }
          });
        });
      } else {
        if (this.distribution.isSelect(2, this, "请先选择门店！")) {
          this.$confirm("确定要取消对这些门店的分配吗？", {
            center: true,
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
            closeOnClickModal: false,
            closeOnPressEscape: false
          }).then(() => {
            cancelDistribution(data).then(res => {
              if (res.code == 200) {
                this.$refs.multipleTable.clearSelection();
                this._distribution(this.nameType, this.idType, this.actName);
                this.$message.success(res.msg);
              }
            });
          });
        }
      }
    },
    // 删除一条活动
    deleteRows(id, activityState) {
      this.$confirm("确定要删除吗?", "提示", {
        center: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        closeOnClickModal: false,
        closeOnPressEscape: false
      })
        .then(async () => {
          if (activityState == "1") {
            this.$alert("活动已经启动，不能删除", {
              confirmButtonText: "确定",
              center: true,
              callback: action => {
                this.information();
              }
            });
          } else {
            let data = {
              activityId: id,
              dr: 1
            };
            offActivity(data).then(res => {
              if (res.code == 200) {
                this.information();
                this.$message.success(res.msg);
              }
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    }
  }
};
</script>

<style scoped>
.newWhole {
  width: 100%;
  overflow: hidden;
  box-sizing: border-box;
}
.header {
  display: flex;
  width: 100%;
  padding: 10px 0px;
}
.cont {
  padding: 20px 10px 20px 10px;
  display: flex;
  justify-content: space-around;
}
.block {
  padding: 10px 0;
}
.header .search-input {
  width: 180px;
  margin-right: 10px;
}
.header .el-select {
  margin-right: 20px;
}
.header label {
  line-height: 32px;
  margin-right: 10px;
}
</style>
<style lang="">
.demo .el-switch__label {
  position: absolute;
  display: none;
  color: #fff;
}
/*打开时文字位置设置*/
.demo .el-switch__label--right {
  z-index: 1;
  right: -3px;
}
/*关闭时文字位置设置*/
.demo .el-switch__label--left {
  z-index: 1;
  left: 19px;
}
/*显示文字*/
.demo .el-switch__label.is-active {
  display: block;
}
.demo.el-switch .el-switch__core,
.demo.el-switch .el-switch__label {
  width: 50px !important;
  text-align: left;
}
</style>
